package com.itheima.controller;

import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;

import com.itheima.service.CheckItemService;
import com.itheima.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private HttpServletResponse resp;

    @Autowired
    private HttpServletRequest req;

    @PostMapping("/login.do")
    public Result login(String username, String password) {


        Result result = loginService.findUser(username, password);

        if (result.isFlag()) {

            try {
                resp.sendRedirect("http://localhost:8080/pages/main.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                resp.sendRedirect("http://localhost:8080/login.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @GetMapping("/user/getUsername.do")
    @ResponseBody
    public Result getUsername() {
        HttpSession session = req.getSession();
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return new Result(false, "请先登录");
        }
        return new Result(true, "获取当前登录用户名称成功", username);
    }

}
